import db from '../utils/dbconf';
import makeres from '../utils/res';
import TokenTools from './tools/token';
import CodeTools from './tools/code';
import { ParameterError, AuthError } from '../utils/classModal';

export const TABLE_NAME = 'USER';

export default {
	login: async ({ body: { account, password } }, res, next) => {
		if (!account || !password) throw new Error('请输入账号&&密码');
		const uinfo = await db.table(TABLE_NAME).where({ account, password }).field('account,password', true).find();
		const { id: u_id, level, dis } = uinfo;
		if (!u_id) throw new Error('账号或密码错误');
		if (dis) throw new Error('账号已被禁用，具体原因请咨询管理员');
		const token = await TokenTools.create({ u_id, level }); // 创建并更新token
		delete uinfo.id;
		delete uinfo.dis;
		const data = { ...uinfo, token };
		return res.send(makeres.success(data, '登录成功'));
	},
	register: async ({ body: { account, password, mail, code } }, res, next) => {
		const codeid = await CodeTools.checkCode(mail, code);
		const level = 9;
		const nickname = '新用户-' + Date.now();
		const { type, id } = await db
			.table(TABLE_NAME)
			.thenAdd({ account, password, mail, nickname, level }, { account, mail }, true);
		if (type === 'exist') throw new Error('用户名已存在 / 邮箱已被注册');
		await db.table(TABLE_NAME).where({ id }).update({ u_id: id });
		await CodeTools.checkOver(codeid);
		return res.send(makeres.success());
	},
	changepassword: async ({ body: { password, newpassword } }, res) => {
		const { u_id: id } = res.locals;
		const real = await db.table(TABLE_NAME).where({ id, password }).count('id');
		if (!real) throw new Error('原密码错误');
		await db.table(TABLE_NAME).where({ id }).update({ password: newpassword });
		await TokenTools.clearToken(id);
		res.send(makeres.success());
	},
	// getuserdetail: async (uinfo) => {
	// 	return uinfo;
	// },
	getcode: async ({ query: { mail } }, res) => {
		await CodeTools.sendReginCode(mail);
		return res.send(makeres.success());
	},
	usertool: async ({ method, params: { id }, body }, res) => {
		const { level, u_id } = res.locals;
		if (isNaN(id)) throw new ParameterError();
		if (level !== 999 && u_id !== id) throw new AuthError();
		switch (method) {
			case 'GET':
				const uinfo = await db.table(TABLE_NAME).where({ id }).find();
				return res.send(makeres.success(uinfo));
			case 'PUT':
				await db.table(TABLE_NAME).update({ id, ...body });
				return res.send(makeres.putsuccess());
			case 'DELETE':
				await db.table(TABLE_NAME).delete({ id });
				return res.send(makeres.deletesuccess());
		}
	},
};
